import { loginAPI } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: ''
}

const mutations = {
  // 用户登录
  LOGIN(state, options) {
    state.token = options
    setToken(options)
  },
  // 用户退出
  LOGOUT(state) {
    // 删除缓存的token和用户信息
    state.token = null
    removeToken()
  }
}

const actions = {
  // 用户登录
  async login({ commit }, userInfo) {
    const { data } = await loginAPI(userInfo)
    commit('LOGIN', data)
  },
  // 用户退出
  logout({ commit }) {
    commit('LOGOUT')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
